#include "song_list_interface.h"
#include "ui_song_list_interface.h"

#include <QTimer>
#include <QDebug>
#include <QListWidgetItem>
#include <QMessageBox>

song_list_interface::song_list_interface(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::song_list_interface)
{
    ui->setupUi(this);
    // 设置大小策略，使其可以扩展
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 连接返回按钮
    connect(ui->pushButton_3, &QPushButton::clicked, this, &song_list_interface::on_backButton_clicked);

    // 连接删除歌曲按钮
    connect(ui->pushButton, &QPushButton::clicked, this, &song_list_interface::on_deleteButton_clicked);

    // 连接列表项双击信号
    connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, &song_list_interface::on_listWidget_itemDoubleClicked);
}

song_list_interface::~song_list_interface()
{
    delete ui;
}

void song_list_interface::setPlaylistName(const QString& name)
{
    currentPlaylistName = name;
    ui->label_2->setText(name); // 修改为设置 label_2 的文本
}

void song_list_interface::loadPlaylistContent(const QString& content)
{
    ui->listWidget->clear();
    if (!content.isEmpty()) {
        QStringList songs = content.split('\n', Qt::SkipEmptyParts);
        for (const QString& song : songs)
        {
            ui->listWidget->addItem(song);
        }
    }
}
//获取当前选中的歌曲项
QListWidgetItem *song_list_interface::getCurrentSongItem()
{
    if (ui->listWidget) { // 避免空指针
        return ui->listWidget->currentItem();
    }
    return nullptr;
}

// 实现返回按钮的槽函数
void song_list_interface::on_backButton_clicked()
{
    qDebug() << "返回按钮被点击";

    // 先发射信号，然后再隐藏
    emit backToPlaylist();

    // 延迟隐藏，避免布局冲突
    QTimer::singleShot(10, this, [this]() {
        this->hide();
    });
}

// 删除歌曲按钮的槽函数
void song_list_interface::on_deleteButton_clicked()
{
    QListWidgetItem *currentItem = ui->listWidget->currentItem();
    if (!currentItem) {
        QMessageBox::warning(this, "提示", "请选择要删除的歌曲！");
        return;
    }

    QString songInfo = currentItem->text();

    int ret = QMessageBox::question(this, "确认删除",
                                   QString("确定要从歌单\"%1\"中删除歌曲\"%2\"吗？")
                                   .arg(currentPlaylistName).arg(songInfo),
                                   QMessageBox::Yes | QMessageBox::No);

    if (ret == QMessageBox::Yes) {
        // 发射删除歌曲信号
        emit deleteSongRequested(songInfo);

        // 从列表中删除
        delete ui->listWidget->takeItem(ui->listWidget->row(currentItem));

        QMessageBox::information(this, "提示", "歌曲删除成功！");
    }
}

// 列表项双击槽函数
void song_list_interface::on_listWidget_itemDoubleClicked()
{
    qDebug() << "歌曲被双击，进入歌词界面";
    emit songDoubleClicked();
}
